package com.manager.commons.tag.selected;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.manager.commons.basemanage.commons.SelectStaticData;
import com.manager.commons.basemanage.entity.BaseDataList;


public class SelectTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	/**
	 * 日志
	 */
	private Logger log = Logger.getLogger(this.getClass());

	// 数据源来源于数据字典
	private final String DATADOURCE_DICTIONARY = "dictionary";

	// 数据源来源于集合
	private final String DATADOURCE_COLLECTION = "collection";

	// 下拉框的name名称
	private String defaultName = "";

	// 父id
	private String pid = "0";

	// 样式
	private String styles;

	// 默认选择值
	private String propertyName;

	// 初始化列表list
	@SuppressWarnings("unchecked")
	List selectList = null;

	// 储存输出页面的字符串
	StringBuffer stringBuffer = null;

	// 储存输出页面的字符串
	String type = null;

	// onClick事件
	private String onClickValue;

	// onChange事件
	private String onChangeValue;

	// 显示为文本样式
	private final String TEXT_TYPE = "3";

	// 数据源来源 默认是数据字典
	private String dataSource = DATADOURCE_DICTIONARY;

	// 数据源为集合时 的 值
	private String value;

	// 数据源为集合时 的 显示属性
	private String property;
	
	//是否显示第一项请选择
	private String firstShow;
	
	private boolean readonly = false;
    
	private String id;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	// 标签初始化select
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

		try {
			pageContext.getOut().print(getBaseTypeTbBuffer());
		}
		catch(Exception e) {
//			System.out.print("下拉列表标签出错，信息如下：" + e.getMessage());
		}

		return SKIP_BODY;
	}

	/**
	 * @Description: 站点名称下拉列表结果字符
	 * @return StringBuffer
	 */
	private StringBuffer getBaseTypeTbBuffer() {

		// 储存输出页面的字符串
		stringBuffer = new StringBuffer();
		// 数据来源于数据字典
		if(dataSource.equals(DATADOURCE_DICTIONARY)) {
			if(type.equals("5")||type.equals("6")) {
				stringBuffer = getDataFromDictionaryD(stringBuffer);
			}
			else{
				stringBuffer = getDataFromDictionary(stringBuffer);
			}
		} else if(dataSource.equals(DATADOURCE_COLLECTION)) { // //数据来源于集合
			try {
				stringBuffer = getDataFromCollection(stringBuffer);
			}
			catch(Exception ex) {
				log.debug("集合中不存在相应的属性！");
			}

		}
		return stringBuffer;
	}
	// 数据来源于数据字典
	private StringBuffer getDataFromDictionaryD(StringBuffer stringBuffer) {
		List selectList = (List) SelectStaticData.get(pid);
		BaseDataList baseDataList = new BaseDataList();
        Collections.sort(selectList,new CompareDict());
		if(type.equals(TEXT_TYPE)) {
			for(int i = 0; i < selectList.size(); i++) {
				// 获得对象
				baseDataList = (BaseDataList) selectList.get(i);
				if(baseDataList.getListCode().toString().equals(defaultName)) {
					stringBuffer.append(baseDataList.getListName());
				}
			}
			return stringBuffer;

		}
        if(StringUtils.isBlank(id)){
        	if(propertyName.indexOf("*")>=0){
        		propertyName = propertyName.substring(propertyName.indexOf("*")+1);
        	}
        	id = propertyName;
        }
		if(onClickValue != null && !onClickValue.equals("")) {
			onClickValue = "onClick=\"" + onClickValue + "\"";
		} else
			onClickValue = "";
		if(onChangeValue != null && !onChangeValue.equals("")) {
			onChangeValue = "onChange=\"" + onChangeValue + "\"";
		} else
			onChangeValue = "";


		for(int i = 0; i < selectList.size(); i++) {
			// 获得对象
			baseDataList = (BaseDataList) selectList.get(i);
			if(type.equals("5")) {
				if(defaultName.indexOf(baseDataList.getListCode().toString())>-1) {
					stringBuffer.append("<input type='checkbox' style=\"" + styles + "\"" + onClickValue + " " 
							+ onChangeValue + " name=\"" + propertyName + "\" value=\"" + baseDataList.getListCode() + "\"  " );
					if(readonly){
						stringBuffer.append(" readonly='readonly' " );
					}
					stringBuffer.append(" checked=\"checked\" />" + baseDataList.getListName());
				} else {
					stringBuffer.append("<input type='checkbox' style=\"" + styles + "\"" + onClickValue + " " 
							+ onChangeValue + " name=\"" + propertyName + "\" value=\"" + baseDataList.getListCode() + "\" "  );
					if(readonly){
						stringBuffer.append(" readonly= 'readonly' " );
					}
							stringBuffer.append("/>" + baseDataList.getListName());
				}
			} else {
				if(defaultName.indexOf(baseDataList.getListName().toString())>-1) {
					stringBuffer.append("<input type='checkbox' style=\"" + styles + "\"" + onClickValue + " " 
							+ onChangeValue + " name=\"" + propertyName + "\" value=\"" + baseDataList.getListName() + "\" "  );
					if(readonly){
						stringBuffer.append("  readonly='readonly' " );
					}
					stringBuffer.append(" checked=\"checked\" />" + baseDataList.getListName());
				} else {
					stringBuffer.append("<input type='checkbox' style=\"" + styles + "\"" + onClickValue + " " 
							+ onChangeValue + " name=\"" + propertyName + "\" value=\"" + baseDataList.getListName() );
					if(readonly){
						stringBuffer.append(" readonly= 'readonly' " );
					}
					stringBuffer.append("\" />" + baseDataList.getListName());
				}
			}
		}
		return stringBuffer;
	}
	// 数据来源于数据字典
	private StringBuffer getDataFromDictionary(StringBuffer stringBuffer) {
		List selectList = (List) SelectStaticData.get(pid);
		BaseDataList baseDataList = new BaseDataList();
        Collections.sort(selectList,new CompareDict());
		if(type.equals(TEXT_TYPE)) {
			for(int i = 0; i < selectList.size(); i++) {
				// 获得对象
				baseDataList = (BaseDataList) selectList.get(i);
				if(baseDataList.getListCode().toString().equals(defaultName)) {
					stringBuffer.append(baseDataList.getListName());
				}
			}
			return stringBuffer;

		}
        if(StringUtils.isBlank(id)){
        	if(propertyName.indexOf("*")>=0){
        		propertyName = propertyName.substring(propertyName.indexOf("*")+1);
        	}
        	id = propertyName;
        }
		if(onClickValue != null && !onClickValue.equals("")) {
			onClickValue = "onClick=\"" + onClickValue + "\"";
		} else
			onClickValue = "";
		if(onChangeValue != null && !onChangeValue.equals("")) {
			onChangeValue = "onChange=\"" + onChangeValue + "\"";
		} else
			onChangeValue = "";

		stringBuffer.append("<select id=\'"+ id +"\' ");
		if(readonly){
			stringBuffer.append("  disabled " );
		}
		stringBuffer.append("  style=\"" + styles + "\"" + onClickValue + " " + onChangeValue + " name=\"" + propertyName + "\">\n");
		if(firstShow!=null && firstShow.equals("N")){
		}else{
			stringBuffer.append("<option value=\"" + "\" selected>" + "----请选择----" + "</option>\n");
		}
		// }

		for(int i = 0; i < selectList.size(); i++) {
			// 获得对象
			baseDataList = (BaseDataList) selectList.get(i);
			if(type.equals("1")) {
				if(baseDataList.getListCode().toString().equals(defaultName)) {
					stringBuffer.append("<option value=\"" + baseDataList.getListCode() + "\"   selected>" + baseDataList.getListName() + "</option>\n");
				} else {
					stringBuffer.append("<option value=\"" + baseDataList.getListCode() + "\" >" + baseDataList.getListName() + "</option>\n");
				}
			} else {
				if(baseDataList.getListName().toString().equals(defaultName)) {
					stringBuffer.append("<option value=\"" + baseDataList.getListName() + "\"  selected>" + baseDataList.getListName() + "</option>\n");
				} else {
					stringBuffer.append("<option value=\"" + baseDataList.getListName() + "\" >" + baseDataList.getListName() + "</option>\n");
				}
			}
		}
		stringBuffer.append("</select>\n");
		return stringBuffer;
	}

	// 数据来源于数据字典集合
	private StringBuffer getDataFromCollection(StringBuffer stringBuffer) throws Exception {
		String selectValue = "";
		Iterator it = selectList.iterator();
		if(type.equals(TEXT_TYPE)) {
			while(it.hasNext()) {
				Object objectBean = it.next();
				//处理Map的情况
				if(objectBean instanceof Map){
					Map tempMap = (Map) objectBean;
					Iterator mapIterator = tempMap.entrySet().iterator();
					while(mapIterator.hasNext()){
						Map.Entry entry = (Entry) mapIterator.next();
						selectValue = (String) entry.getKey();
						if(selectValue.equals(defaultName)) {
							stringBuffer = new StringBuffer(entry.getValue().toString());
							break;
						}
					}
				}else{
					selectValue = BeanUtils.getProperty(objectBean, this.value);
					if(selectValue.equals(defaultName)) {
						stringBuffer = new StringBuffer(BeanUtils.getProperty(objectBean, this.property));
						break;
					}
				}
			}
			return stringBuffer;

		}
        if(StringUtils.isBlank(id)){
        	if(propertyName.indexOf("*")>=0){
        		propertyName = propertyName.substring(propertyName.indexOf("*")+1);
        	}
        	id = propertyName;
        }
		if(onClickValue != null && !onClickValue.equals("")) {
			onClickValue = "onClick=\'" + onClickValue + "\'";
		} else
			onClickValue = "";
		if(onChangeValue != null && !onChangeValue.equals("")) {
			onChangeValue = "onChange=\'" + onChangeValue + "\'";
		} else
			onChangeValue = "";

		stringBuffer.append("<select id=\'"+ id +"\' ");
		if(readonly){
			stringBuffer.append("  disabled " );
		}
		stringBuffer.append(" style=\'" + styles + "\'" + onClickValue + " " + onChangeValue + " name=\'" + propertyName + "\'>");
		if(firstShow!=null && firstShow.equals("N")){
		}else{
			stringBuffer.append("<option value=\'" + "\' selected>" + "----请选择----" + "</option>");
		}
		
		// }

		while (it.hasNext()) {
			String objectValue = "";
			String objectProperty = "";
			// 获得对象
			Object objectBean = it.next();
			if(objectBean instanceof Map){
				Map tempMap = (Map) objectBean;
				Iterator mapIterator = tempMap.entrySet().iterator();
				while(mapIterator.hasNext()){
					Map.Entry entry = (Entry) mapIterator.next();
					objectValue = (String) entry.getKey();
					objectProperty = entry.getValue().toString();
					if(objectValue.equals(defaultName)) {
						stringBuffer.append("<option value=\'" + objectValue + "\'  selected>" + objectProperty + "</option>");
					} else {
						stringBuffer.append("<option value=\'" + objectValue + "\' >" + objectProperty + "</option>");
					}
				}
			}else{
				objectValue = BeanUtils.getProperty(objectBean, this.value);
				objectProperty = BeanUtils.getProperty(objectBean, this.property);
				if(objectValue.equals(defaultName)) {
					stringBuffer.append("<option value=\'" + objectValue + "\'  selected>" + objectProperty + "</option>");
				} else {
					stringBuffer.append("<option value=\'" + objectValue + "\' >" + objectProperty + "</option>");
				}
			}



		}
		stringBuffer.append("</select>");
		return stringBuffer;
	}
	
	

	public String getDefaultName() {
		return defaultName;
	}

	public void setDefaultName(String defaultName) {
		this.defaultName = defaultName;
	}

	public String getPropertyName() {
		return propertyName;
	}

	public void setPropertyName(String propertyName) {
		this.propertyName = propertyName;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public List getSelectList() {
		return selectList;
	}

	public void setSelectList(List selectList) {
		this.selectList = selectList;
	}

	public String getOnChangeValue() {
		return onChangeValue;
	}

	public void setOnChangeValue(String onChangeValue) {
		this.onChangeValue = onChangeValue;
	}

	public String getOnClickValue() {
		return onClickValue;
	}

	public void setOnClickValue(String onClickValue) {
		this.onClickValue = onClickValue;
	}

	public String getStyles() {
		return styles;
	}

	public void setStyles(String styles) {
		this.styles = styles;
	}

	public String getDataSource() {
		return dataSource;
	}

	public void setDataSource(String dataSource) {
		this.dataSource = dataSource;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getFirstShow() {
		return firstShow;
	}

	public void setFirstShow(String firstShow) {
		this.firstShow = firstShow;
	}
    
	class CompareDict implements Comparator{

		public int compare(Object obj1, Object obj2) {
			BaseDataList basedataOne = (BaseDataList) obj1;
			BaseDataList basedataTwo = (BaseDataList) obj2;
			return basedataOne.getListCode().compareTo(basedataTwo.getListCode());
		}
		
	}

	public boolean isReadonly() {
		return readonly;
	}

	public void setReadonly(boolean readonly) {
		this.readonly = readonly;
	}
}

